<?php

	class orders {
		

		function orders() {
			global $admin,$db,$config;
			if ($_POST['act']=='export'){
				$params=$_GET;
				$sqlstr = "select a.id,a.shop,b.pid,a.productid,a.product,d.barcode,a.spec,a.unit,a.number,a.type,a.lotnumber,FROM_UNIXTIME(a.thedate, '%Y-%m-%d' )as thedate,a.timestocked from {$config->db_prefix}orders as a left join haiou_product_sku as b on a.productid=b.id left join {$config->db_prefix}products as d on a.productid=d.product_sku_id where 1=1";
			if (!empty($params['id'])) $sqlstr .= " and id = ".$db->qstr($params['id']);
			if (!empty($params['shopid'])) $sqlstr .= " and shopid = ".$db->qstr($params['shopid']);
			if (isset($params['keywords'])) $sqlstr .= " and b.pname like ". $db->qstr("%".$params['keywords']."%");
			if (!empty($params['sdate'])) $sqlstr .= " and thedate>=". strtotime($params['sdate']);
			if (!empty($params['edate'])) $sqlstr .= " and thedate<=". (strtotime($params['edate'])+86399);
			if (!empty($params['lnumber'])) $sqlstr .= " and number>=". $db->qstr($params['lnumber']);
			if (!empty($params['hnumber'])) $sqlstr .= " and number<=". $db->qstr($params['hnumber']);
			if (!empty($params['lotnumber'])) $sqlstr .= " and lotnumber like ". $db->qstr("%".$params['lotnumber']."%");
			if (!empty($params['barcode'])) $sqlstr .= " and d.barcode=".$db->qstr($params['barcode']);
			if (!empty($params['product_id'])) $sqlstr .= " and b.pid in(".$params['product_id'].")";
			
			if (!empty($params['cond'])) $sqlstr .= " and ({$params['cond']})";
			
			if($params['type']!==null&&$params['type']!==''){
			    $sqlstr .= " and type= {$params['type']}";
			}
			if($params['status']==''){
				$params['status'] = '0';
			}	
			if($params['status']==="0"){
			    $sqlstr .= " and timestocked= 0";
			}elseif ($params['status']==="1"){
			    $sqlstr .= " and timestocked> 0";
			}elseif ($params['status']==="-1"){
			    $sqlstr .= " and timestocked= -1";
			}

			if (!empty($params['counter'])) $counter = $db->getrow(str_replace("*", "sum(number) number", $sqlstr));
			if (!empty($params['order'])) $sqlstr .= " order by {$params['order']}";
				include_once '../lib/php_excel.php';
				$export_data=$db->GetArray($sqlstr);
				foreach ($export_data as $key=> $var)
				{
					$export_data[$key]['number']=intval($export_data[$key]['number']);
					$export_data[$key]['type'] = $config->orders_type[$var['type']];
					
					if($export_data[$key]['timestocked'] == '0')
					{
						$export_data[$key]['timestocked'] = '未处理';
					}else if($export_data[$key]['timestocked'] > '0')
					{
						$export_data[$key]['timestocked'] = '已出库';
					}else if($export_data[$key]['timestocked'] < '0')
					{
						$export_data[$key]['timestocked'] = '未出库';
					}
					if($export_data[$key]['lotnumber'] == '')
					{
						$export_data[$key]['type']=$export_data[$key]['type'];
					}else 
					{
						$export_data[$key]['type']=$export_data[$key]['type'].'('.$export_data[$key]['lotnumber'].')';
					}
					$export_data[$key]['lotnumber'] = $export_data[$key]['thedate'];
					$export_data[$key]['thedate'] = $export_data[$key]['timestocked'];
					$export_data[$key]['timestocked'] = '';
// 					$export_data[$key]['spec']=intval($export_data[$key]['number']).$export_data[$key]['unit'];
				}
				$queue[0] = array("序号","仓库","产品ID","SKU_ID","产品名称","条码","规格","单位","出库数量","出库类型","出库时间","出库状态");//定义表头
				$export_data = array_merge($queue,$export_data);
				/*  print_r($export_data);
				 exit; */
				$filename =   "出库信息" . date ( "YmdHis" );
				$xls = new Excel_XML ( 'UTF-8', false, '出库信息' );
				$xls->addArray ( $export_data );
				$xls->generateXML ( $filename );
				exit ();
			}
			//if(empty($_SESSION["managerid"])) $admin->login();
		}
		
		function index() {
			global $admin,$config,$smarty;
			$smarty->assign('type',$config->orders_type);
				
			//if(!$admin->rights("orders_view")) return;
		}


		function create() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("orders_create")) return;
			unset($config->orders_type[0]);
			$smarty->assign('type',$config->orders_type);
			if(!empty($_POST["action"]) && $_POST["action"]=="create") {

				$thedate = strtotime($_POST["Date_Year"]."-".$_POST["Date_Month"]."-".$_POST["Date_Day"]);
				$smarty->assign("thedate", $thedate);
				
				if(empty($_POST["shopid"])) $errors["empty_shopid"] = true;
				if(empty($_POST["product"])) $errors["empty_product"] = true;
				if(empty($_POST["number"]) || $_POST["number"]==0) $errors["empty_number"] = true;
				
				$productid = $db->qstr($_POST["productid"]);
				if(empty($errors)) if(!$productid) $errors["unexist_product"] = true;

				if(empty($errors)) {
					$shopid = $db->qstr($_POST["shopid"]);
					$shop = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid"));
					$product = $db->qstr($_POST["product"]);
					$spec = $db->qstr($_POST["spec"]);
					$pricesell = $db->qstr(empty($_POST["pricesell"])?0:$_POST["pricesell"]);
					$unit = $db->qstr($_POST["unit"]);
					$number = $db->qstr($_POST["number"]);
					$memo = $db->qstr($_POST["memo"]);
					
					$type = $db->qstr($_POST["type"]);
						
					
					$sqlstr = "insert into {$config->db_prefix}orders (shopid, shop, productid, product, spec, unit, number, memo,type, thedate) value ($shopid, $shop, $productid, $product, $spec, $unit, $number, $memo,$type, $thedate)";
					$result = $db->execute($sqlstr);
					if($result) header("location:{$config->site_admin}m=inventory&s=orders.php");
									}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
		}
		
		
		function modify() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("orders_modify")) return;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="modify") {

				$thedate = strtotime($_POST["Date_Year"]."-".$_POST["Date_Month"]."-".$_POST["Date_Day"]);
				$smarty->assign("thedate", $thedate);
				
				if(empty($_POST["shopid"])) $errors["empty_shopid"] = true;
				if(empty($_POST["product"])) $errors["empty_product"] = true;
				if(empty($_POST["number"]) || $_POST["number"]==0) $errors["empty_number"] = true;
				
				$productid = $db->qstr($_POST["productid"]);
				if(empty($errors)) if(!$productid) $errors["unexist_product"] = true;

				if(empty($errors)) {
					$id = $db->qstr($_POST["id"]);
					$shopid = $db->qstr($_POST["shopid"]);
					$shop = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid"));
					$product = $db->qstr($_POST["product"]);
					$spec = $db->qstr($_POST["spec"]);
					$unit = $db->qstr($_POST["unit"]);
					$number = $db->qstr($_POST["number"]);
					$memo = $db->qstr($_POST["memo"]);
					
					$sqlstr = "update {$config->db_prefix}orders set shopid=$shopid, shop=$shop, productid=$productid, product=$product, spec=$spec, unit=$unit, number=$number, memo=$memo, thedate=$thedate where id=$id";
					$result = $db->execute($sqlstr);
					if($result) header("location:".(empty($_POST["referer"])?"{$config->site_admin}m=inventory&s=orders.php":$_POST["referer"]."&page=".$_POST['list_page']));
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
		}


		function remove() {
			global $db, $segment, $config, $admin;
			//if(!$admin->rights("orders_delete")) return;
			
			$id = $db->qstr($_GET['orders_id']);
			$sqlstr = "delete from {$config->db_prefix}orders where id=$id";
			$result = $db->execute($sqlstr);
			if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=orders.php":$_SERVER['HTTP_REFERER']));
		}
		function stockconfirm(){
		    global $db, $segment, $config, $smarty;
		    //批量出库
		    if($_POST['act'] && $_POST['act']=='op' && !empty($_POST['chk'])){
		    	foreach ($_POST['chk'] as $ordersid)
		    	{
		    		$this->stockconfirm_one($ordersid);
		    	}
		    	header("location:".(empty($_GET['REFERER'])?"{$config->site_admin}m=inventory&s=orders.php":$_GET['REFERER']));
		    }else{//单个出库
		    	$ordersid = $db->qstr($_GET['orders_id']);
		    	$result = $this->stockconfirm_one($ordersid);
		    	if($result['error']==0){
		    		header("location:".(empty($_GET['REFERER'])?"{$config->site_admin}m=inventory&s=orders.php":$_GET['REFERER']));
		    	}elseif ($result['error']==1)
		    	{
		    		if($_GET['REFERER']){
		    			foreach ($result['error']['msg'] as $k=>$v){
		    				$_GET['REFERER'].='&'.$k.'='.$v;
		    			}
		    			header("location:".$_GET['REFERER']);
		    		}else{
		    			header("location:{$config->site_admin}m=inventory&s=orders.php");
		    		}
		    	}elseif ($result['error']==2){
		    		if($_GET['REFERER']){
		    			header("location:".$_GET['REFERER']);
		    		}
		    	}
		    }
		}
		//出库一个商品
		private function stockconfirm_one($ordersid){
			global $db, $segment, $config, $smarty;
			$rss = $db->getrow("select * from {$config->db_prefix}orders where id=$ordersid and timestocked=0");
			
			if($rss) {
				$shopid = $db->qstr($rss["shopid"]);
				$shop = $db->qstr($rss["shop"]);
				$productid = $db->qstr($rss["productid"]);
				$product = $db->qstr($rss["product"]);
				$spec = $db->qstr($rss["spec"]);
				$unit = $db->qstr($rss["unit"]);
				$number = $rss["number"]+0;
				 
			
				$stock = $db->getrow("select * from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
				//$canbuy =$db->getrow("select canbuyout from {$config->db_prefix}products where  and id=$productid");
				if(!$stock) $errors["unexisted_product"] = true;
				else if($stock["stocks"]<$number) $errors["notenough_stocks"] = true;
				//else if($stock["stocks"]==$number) $sqlstr = "delete from {$config->db_prefix}stocks where id=". $stock['id'];
				else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks-$number where id=". $stock['id'];
			
			
				if(empty($errors)) {
					$result = $db->execute($sqlstr);
					$this->_update_product_stocks($productid);
					$this->_delnumber($number,$shopid,$productid,$ordersid);
					 
					if($rss['type']!=0){
						 
						$this->_update_front($productid,$number,$shopid);
					}else{
					    $this->_update_order_product_status($productid, $rss['lotnumber'], 1);
					    //更新已售数量
					    $sql = "update {$config->db_prefix}stocks set sold_num=sold_num-{$number} where id=". $stock['id'];
					    $db->execute($sql);
					}
			
					 
			
					$timestocked = time();
					$sqlstr = "update {$config->db_prefix}orders set timestocked=$timestocked where id=$ordersid";
					$result = $db->execute($sqlstr);
					
					//如果是调拨出库则创建一条入库记录
					if($rss['type']==5){
					    //查询调拨单信息
					    $sql = "select * from {$config->db_prefix}moving_paper where id={$rss['lotnumber']}";
					    $paperInfo = $db->GetRow($sql);
					    
					    //产品信息
					    $sql = "select a.pricebuy,a.supplieid,b.title from {$config->db_prefix}products a left join {$config->db_prefix}suppliers b on a.supplieid=b.id where product_sku_id={$productid}";
					    $proInfo = $db->GetRow($sql);
					    
					    $timestart = strtotime(date('Y-m-d'));
					    $usedby="+365day";
					    $timeend=strtotime($usedby,$timestart);
					    $usedby= $db->qstr($usedby);
					    
					    $sqlstr = "insert into {$config->db_prefix}purchases 
					    (paper_id,shopid, shop, productid, product, spec, unit, pricebuy, realpricebuy, 
					    number, supplierid, supplier, memo, timeexpress,lotnumber,usedby,
					    timestart,timeend,type,puser ) values 
					    ('{$rss['lotnumber']}}','{$paperInfo['shopid_to']}', '{$paperInfo['shop_to']}', $productid, $product, $spec, $unit, '{$proInfo['pricebuy']}', '{$proInfo['pricebuy']}',
					    '$number', '{$proInfo['supplieid']}', '{$proInfo['title']}', '调拨入库自动写入', '".strtotime(date('Y-m-d'))."','{$rss['lotnumber']}',
					    $usedby,'$timestart','$timeend',5,'系统')";
					    $result = $db->execute($sqlstr);
					}
					return array('error'=>0,'msg'=>'');
				}else{
					return array('error'=>1,'msg'=>$errors);
				}
			}else{
				return array('error'=>2,'msg'=>'');
			}
		}
		
		function stockcancel(){
		    global $db, $segment, $config, $smarty;
		    $ordersid = $db->qstr($_GET['orders_id']);
	    	$rss = $db->getrow("select * from {$config->db_prefix}orders where id=$ordersid");
	    	if($rss['type']==0){
	    		$orderStatus = $db->getrow("select status from ".ORDER." where order_id={$rss['lotnumber']} ");
	    		$otherPro = $db->getrow("select * from {$config->db_prefix}orders where lotnumber={$rss['lotnumber']} and timestocked>=0 and id!=$ordersid");
	    		if(empty($otherPro) && $orderStatus['status']>0){
	    			echo "<script>
	    					alert('无法取消，该订单只有一个待出库产品。');
	    					window.location.href = '".(empty($_GET['REFERER'])?"{$config->site_admin}m=inventory&s=orders.php":$_GET['REFERER'])."';
    					</script>";
	    			exit;
	    		}
	    	}
		    $sqlstr = "update {$config->db_prefix}orders set timestocked=-1 where id=$ordersid and timestocked=0";
		    $result = $db->execute($sqlstr);
		    if ($result){
		    	$productid = $db->qstr($rss["productid"]);
		    	$number = $rss["number"]*-1;
		    	if($rss['type']==0){
		    	    //如果有微仓出的商品，放回微仓
		    	    $microStockInfo = $db->getrow("select microstock_num,member_id from haiou_order_product where order_id={$rss['lotnumber']} and product_id={$productid}");
		    	    if($microStockInfo['microstock_num']>0){
		    	        //更新微仓库存
		    	        $db->execute("update haiou_micro_stock set num=num+{$microStockInfo['microstock_num']} where member_id={$microStockInfo['member_id']} and sku_id={$productid}");
		    	        //删除微仓出库记录
		    	        $db->execute("delete from haiou_micro_stock_out where member_id={$microStockInfo['member_id']} and order_id={$rss['lotnumber']} and sku_id={$productid}");
		    	    }
		    	    //加回前台库存
		    		$this->_update_front($productid,$number);
		    		//更新订单商品表为未出库
		    		$this->_update_order_product_status($productid, $rss['lotnumber'], -1);
		    		//更新已售数量
		    		$sql = "update {$config->db_prefix}stocks set sold_num=sold_num+{$number} where productid={$productid} and shopid={$rss['shopid']}";
		    		$db->execute($sql);
		    	}else{
					}
		    }
		    if($result) header("location:".(empty($_GET['REFERER'])?"{$config->site_admin}m=inventory&s=orders.php":$_GET['REFERER']));
		
		
		}
		function _update_product_stocks($productid) {
		    global $db, $segment, $config, $smarty;
		    	
		    $stocks = $db->getone("select sum(stocks) from {$config->db_prefix}stocks where productid=$productid");
		    if(!$stocks) $stocks = 0;
		    $result = $db->execute("update {$config->db_prefix}products set stocks=$stocks where product_sku_id=$productid");
		    return $result;
		}
		
		function _update_front($productid,$number,$shopid=0){
			
			global $db, $segment, $config;
				
// 			$product = $db->getone("SELECT `stock` FROM `haiou_product_sku` WHERE `id`={$productid}");
			return $db->execute("update haiou_product_sku set stock=stock-($number) where id=$productid and stock_shop={$shopid}");
		}
		
		
		function _update_order_product_status($productid,$order_id,$status){
		    global $db, $segment, $config;
		    return $db->execute("update haiou_order_product set is_stocked=$status where order_id=$order_id and product_id=$productid limit 1");
		}
		
		function _delnumber($number,$shopid,$productid,$ordersid){
		    global $db, $segment, $config, $smarty, $admin;
		    $delnumber= $db->getrow("select * from {$config->db_prefix}purchases where shopid=$shopid and productid=$productid and timestocked>0 and number!=delnumber order by timeend asc ");
		    if($delnumber){
		        $purchasesid=$delnumber['id'];
		        $remains=$delnumber['number']-$delnumber['delnumber'];//减掉
		        
		        
		        if($remains>=$number){
		            $sqlstr = "update {$config->db_prefix}purchases set delnumber=".($delnumber['delnumber']+$number)." where id=$purchasesid";
		            $db->execute($sqlstr);
		            $db->execute("insert into {$config->db_prefix}payout (shopid, ordersid, productid, purchasesid, number) value ($shopid,$ordersid,$productid,$purchasesid,$number)");
		            
		            
		        }else{
		            $sqlstr = "update {$config->db_prefix}purchases set delnumber=".($delnumber['number'])." where id=$purchasesid";
		            $db->execute($sqlstr);
		            $db->execute("insert into {$config->db_prefix}payout (shopid, ordersid, productid, purchasesid, number) value ($shopid,$ordersid,$productid,$purchasesid,$remains)");
		            $this->_delnumber($number-$remains, $shopid, $productid, $ordersid);
		            
		        }
		        
		        
		    }else{
		        
		        return false;
		    }
		    
		}
		
		function payout() {
		    global $db, $segment, $config, $smarty, $admin;
		    if(!$admin->rights("payout_view")) return;
		
		    if(!empty($segment[1]) && $segment[1]=="confirm") {
		        if(!$admin->rights("payout_modify")) return;
		
		        $orderid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}orders where id=$orderid and timestocked=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $shop = $db->qstr($rss["shop"]);
		            $productid = $db->qstr($rss["productid"]);
		            $product = $db->qstr($rss["product"]);
		            $spec = $db->qstr($rss["spec"]);
		            $unit = $db->qstr($rss["unit"]);
		            $number = $rss["number"]+0;
		            	
		            $stock = $db->getrow("select * from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stock) $errors["unexisted_product"] = true;
		            else if($stock["stocks"]<$number) $errors["notenough_stocks"] = true;
		            else if($stock["stocks"]==$number) $sqlstr = "delete from {$config->db_prefix}stocks where id=". $stock['id'];
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks-$number where id=". $stock['id'];
		            	
		            if(empty($errors)) {
		                $result = $db->execute($sqlstr);
		                $this->_update_product_stocks($productid);
		
		                $timestocked = time();
		                $sqlstr = "update {$config->db_prefix}orders set timestocked=$timestocked where id=$orderid";
		                $result = $db->execute($sqlstr);
		                if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/payout":$_SERVER['HTTP_REFERER']));
		            }
		            	
		            if(!empty($errors)) $smarty->assign("errors", $errors);
		        }
		    }
		
		    elseif(!empty($segment[1]) && $segment[1]=="cancel") {
		        if(!$admin->rights("payout_modify")) return;
		
		        $orderid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}orders where id=$orderid and timestocked!=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $shop = $db->qstr($rss["shop"]);
		            $productid = $db->qstr($rss["productid"]);
		            $product = $db->qstr($rss["product"]);
		            $spec = $db->qstr($rss["spec"]);
		            $unit = $db->qstr($rss["unit"]);
		            $number = $rss["number"]+0;
		            	
		            //
		            $stockid = $db->getone("select id from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stockid)$sqlstr = "insert into {$config->db_prefix}stocks (shopid, shop, productid, product, spec, unit, stocks) values ($shopid, $shop, $productid, $product, $spec, $unit, $number)";
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks+$number where id=$stockid";
		            $result = $db->execute($sqlstr);
		            $this->_update_product_stocks($productid);
		            	
		            $sqlstr = "update {$config->db_prefix}orders set timestocked=0 where id=$orderid";
		            $result = $db->execute($sqlstr);
		            if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/payout":$_SERVER['HTTP_REFERER']));
		        }
		    }
		    	
		}
		
		

		

}
?>